<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/5
 * Time: 8:58
 */

namespace app\admin\model;


use other\Tree;
use think\Db;
use think\Loader;
use think\Model;

class Category extends Model
{
    protected $autoWriteTimestamp = true;

    public function pages()
    {
        return $this->hasOne('Pages');
    }

    public function cateAdd($data)
    {
        $this->data($data);
        $this->allowField(true)->isUpdate(false)->save();
        if ($data['type'] == 2)
        {
            $this->pages()->save(['title'=>$data['title']]);
        }
        return $this;
    }

    public function cateEdit($data)
    {
        unset($data['thumb_del']);
        $this->update($data);
        $row = $this::hasWhere('pages', ['category_id'=>$data['id']])->find();
        if ($data['type'] == 2)
        {
            if (empty($row))
            {
                $this->pages()->insertGetId(['title'=>$data['title'], 'category_id'=>$data['id'], 'create_time'=>time(), 'update_time'=>time()]);
            }
        } else {
            if (!empty($row))
            {
                Loader::model('Pages')->del('category_id = '.$data['id']);
            }
        }
        return $this;
    }

    /**
     * 递归删除栏目
     * @param $id 栏目id
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function del($id)
    {
        $info = $this->field('id, type, thumb')->where('id', $id)->find();
        $this->where('id', $id)->delete();
        if ($info['type'] == 1)
        {
            $ids = $this->getTotalCategory($id);
            Db::name('article')
                ->where('category_id', 'in', $ids)
                ->update(['del_status'=>1, 'update_time'=>time()]);
        } else {
            Loader::model('Pages')->del('category_id = '.$id);
        }
        if (!empty($info['thumb']))
        {
            $path = './public/'.$info['thumb'];
            if (file_exists($path))
            {
                @unlink($path);
            }
        }
        $subcate = $this->field('id, thumb, type')->where('parentid', $id)->select();
        if (!empty($subcate))
        {
            foreach ($subcate as $key => $value) {
                $this->del($value['id']);
            }
        } else {
            return $this;
        }
    }


    //获取栏目id数组
    protected function getTotalCategory($category)
    {
        $list   = Db::name('category')
            ->field('id, title, parentid, attr')
            ->order('sort desc, create_time desc')
            ->select();
        $tree   = new Tree($list);
        $result = $tree->get_child_key($category);
        return $result;
    }
}